HTTP伺服器端
package main
import (
"net/http"
)
type Refer struct {
handler http.Handler
refer string
}
func (this *Refer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Referer() == this.refer {
this.handler.ServeHTTP(w, r)
} else {
w.WriteHeader(403)
}
}
func myHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("this is handler"))
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
func main() {
referer := &Refer{
handler: http.HandlerFunc(myHandler),
refer: "www.xxx.com",
}
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8080", referer)
}
HTTPS伺服器端
創建憑證
openssl req -newkey ras:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt
package main
import (
"log"
"net/http"
)
func main() {
srv := &http.Server{Addr: ":8088", Handler: http.HandlerFunc(handle)}
log.Printf("Serving on https://0.0.0.0:8088")
log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}
func handle(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
w.Write([]byte("Hello this is a HTTP/2 message!"))
}
用戶端
GET
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://www.xxx.com")
if err != nil {
fmt.Print("err", err)
}
closer := resp.Body
bytes, err := ioutil.ReadAll(closer)
fmt.Println(string(bytes))
}
DELETE
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
url := "http://www.xxx.com/comment/add"
payload := strings.NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"xxxx\"}")
req, _ := http.NewRequest("DELETE", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
POST
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "http://www.xxx.com/comment/add"
body := "{\"userId\":1,\"articleId\":1,\"comment\":\"xxx\"}"
response, err := http.Post(url, "•application/x-www-form-urlencoded", bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("err", err)
}
b, err := ioutil.ReadAll(response.Body)
fmt.Println(string(b))
}
PUT
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
url := "http://www.xxx.com/comment/add"
payload := strings.NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"xxx\"}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
自定義header
headers := http.Header{"token": {"46r6ttyfy67fy"}}
headers.Add("Accept-Charset", "UTF-8")
headers.Set("Host", "www.xxx.com")
headers.Set("Location", "www.xxx.com")