> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/golang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/golang/he-xin-mo-zu/http.md).

# http

## GET request

```go
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

func main() {
    response, err := http.Get("http://golang.org/")
    if err != nil {
        fmt.Printf("%s", err)
        os.Exit(1)
    } else {
        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        if err != nil {
            fmt.Printf("%s", err)
            os.Exit(1)
        }
        fmt.Printf("%s\n", string(contents))
    }
}
```

## HTTP Server

```go
// Writing a basic HTTP server is easy using the
// `net/http` package.
package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "hello\n")
}

func main() {
    http.HandleFunc("/hello", hello)
    http.ListenAndServe(":8090", nil)
}
```

> golang server 重複用到 port 不會提示 error 就算是使用
>
> `log.Fatal(http.ListenAndServe(":8010", nil))`

### ResponseWriter 的寫入的三種方法

```go
w.Write([]byte("OK"))
fmt.Fprintf(w, "OK")
io.WriteString(w, "OK")
```

## 回傳 JSON 的 server

```go
	type User struct { 
     Name  string  `json:"name"` 
}
			
			user := User{Name: "jason"};
			data, err := json.Marshal(user)
			if err != nil {
				log.Fatal(err)
			}
			w.Header().Set("Content-Type", "application/json")
			w.Write(data);
```

## 回傳其他格式

```go
fmt.Fprintf(w, "%d", 123)
```

## 讀取 application/x-www-form-urlencoded

```go
package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	log.Println("Server started on: http://localhost:8050")
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		name := r.FormValue("name")
		city := r.FormValue("city")
		fmt.Println(r.Form)
		fmt.Println(name, city)
	})
	http.ListenAndServe(":8050", nil)
}
```

> POST 必須帶三個必備 Header

![](https://4289429853-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0u4DAQK8tk8n7ia5gg%2F-MG0y5ayt8FYT9Usxb2y%2F-MG1BZFGTlaACJNsNSLV%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202020-08-31%20%E4%B8%8A%E5%8D%889.46.46.png?alt=media\&token=dc2e9b34-9db7-4b58-bb3a-65f38dd12c11)

body

![](https://4289429853-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0u4DAQK8tk8n7ia5gg%2F-MG0y5ayt8FYT9Usxb2y%2F-MG1Bi5BQmbup9BlcUwW%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202020-08-31%20%E4%B8%8A%E5%8D%889.47.32.png?alt=media\&token=aff42238-69af-48b4-a313-49ece732523e)

回傳

![](https://4289429853-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0u4DAQK8tk8n7ia5gg%2F-MG0y5ayt8FYT9Usxb2y%2F-MG1Bn6oG8X2-ATK1LCT%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202020-08-31%20%E4%B8%8A%E5%8D%889.47.54.png?alt=media\&token=f736005f-5d64-4f84-919e-4447ce53e27e)

## 解析 form/data

```go
package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	log.Println("Server started on: http://localhost:8050")
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		r.ParseMultipartForm(0)
		// 後面的參數代表解析緩存 size
		name := r.FormValue("name")
		city := r.FormValue("city")
		fmt.Println(r.Form)
		fmt.Println(name, city)
	})
	http.ListenAndServe(":8050", nil)
}
```
