Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • GET request
  • HTTP Server
  • ResponseWriter 的寫入的三種方法
  • 回傳 JSON 的 server
  • 回傳其他格式
  • 讀取 application/x-www-form-urlencoded
  • 解析 form/data

Was this helpful?

  1. 核心模組

http

GET request

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

// 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 的寫入的三種方法

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

回傳 JSON 的 server

	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);

回傳其他格式

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

讀取 application/x-www-form-urlencoded

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

body

回傳

解析 form/data

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)
}
PreviousSortNextcrypto

Last updated 4 years ago

Was this helpful?