Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created February 15, 2019 14:39
Show Gist options
  • Save joeke80215/f94a12a8be91097c846d284cc2a80bb6 to your computer and use it in GitHub Desktop.
Save joeke80215/f94a12a8be91097c846d284cc2a80bb6 to your computer and use it in GitHub Desktop.
Golang http request demo
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
const testURL = "http://127.0.0.1:8080"
func getMethod() {
resp, err := http.Get(testURL + "/getMethod")
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
log.Println("getMethod: " + string(body))
}
func postMethod() {
resp, err := http.Post(testURL+"/postMethod",
"application/x-www-form-urlencoded",
strings.NewReader("Method=post"))
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
log.Println("postMethod: " + string(body))
}
func postFormMethod() {
resp, err := http.PostForm(testURL+"/postFormMethod",
url.Values{"name": {"JOE"}})
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
log.Println("postFormMethod: " + string(body))
}
type formData struct {
Name string `json:"name"`
Age int `json:"age"`
}
func postJSON() {
fd := formData{"JOE", 28}
b, err := json.Marshal(fd)
if err != nil {
log.Panic(err)
}
resp, err := http.Post(testURL+"/postJSON",
"application/json",
bytes.NewReader(b))
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
log.Print("postJSON: " + string(res))
}
func main() {
getMethod()
postMethod()
postFormMethod()
postJSON()
}
package main
import (
"io/ioutil"
"log"
"net/http"
)
func handle(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Panic(err)
}
defer r.Body.Close()
w.Write(b)
}
func main() {
http.HandleFunc("/getMethod", handle)
http.HandleFunc("/postMethod", handle)
http.HandleFunc("/postFormMethod", handle)
http.HandleFunc("/postJSON", handle)
log.Println("Listen on 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment