บันทึกการเรียน Golang วันที่ 3 - ทำ Web ง่ายๆ ด้วย net/http

Go Aug 28, 2023

เมื่อวาน เรียน Golang ผ่าน A Tour Of Go ยังไม่จบ แต่วันนี้ไม่ได้มาต่อนะครับ ขอข้ามไปที่เรื่อง Web เลย ลองใช้งาน net/http เบื้องต้นดู และลองสร้าง web app ขึ้นมาง่ายๆ โดยเรียนจาก Tutorial นี้

Hello World - Go Web Examples
This examples shows how to create an HTTP server using the net/http package from the standard library. It contains all functionalities about the HTTP protocol.

ก่อนที่จะไปใช้ Framework เลยอยากเริ่มเรียนรู้จาก built-in module ก็เลยลองทำ webserver ขึ้นมาด้วย net/http ธรรมดานี้แหละ

โค๊ดสำหรับ Hello World รันผ่าน port 7777 ก็เป็นแบบนี้ สมมติตั้งชื่อว่า simple-http.go

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello World!")
    })

    http.ListenAndServe(":7777", nil)
}

ทดสอบรันด้วยคำสั่ง:

go run simple-http.go

ทดสอบเปิดเว็บ http://localhost:7777 ดูผลลัพธ์ จะได้ Hello World!

curl http://localhost:7777

Request Handler

ตัว Request Handler จะรับ request จาก client และส่ง response กลับไป มีหน้าตา function คือ

func (w http.ResponseWriter, r *http.Request) {}
  • http.ResponseWriter เอาไว้ response text/plain กลับไป
  • *http.Request - รับ request จาก client

Handle Route ด้วย function handleFunc

http.handleFunc("/endpoint", fn)

เมื่อเรารู้วิธี handle route และก็ req, res แล้ว ก็เลยลองทำอีก function เพื่อส่งกลับไปเป็น JSON ได้ประมาณนี้

package main

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

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello World!")
	})
	http.HandleFunc("/json", handleJson)

	http.ListenAndServe(":7777", nil)
}

func handleJson(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	res := make(map[string]string)
	res["message"] = "Hello World!"

	jsonResponse, err := json.Marshal(res)
	if err != nil {
		log.Fatalf("Error in JSON format. Err : %s", err)
	}

	w.Write(jsonResponse)
	return
}

อธิบายจากที่เขียนโค๊ดมา คือ

  • กำหนด  Content-Type เป็น application/json ผ่าน w.Header().Set()
  • สร้าง json ด้วยคำสั่ง make(map[string]string) และ json.Marsah()
Go by Example: JSON
ผมอ้างอิงการสร้าง JSON จากตัวอย่างนี้

สุดท้าย ก็ลองเพิ่มอีก endpoint นึง เพื่อกำหนด res.status เองเป็น 401 Unauthorized ด้วยคำสั่ง

w.WriteHeader(http.StatusUnauthorized)

สรุป

วันนี้ก็ลองหัดเขียน HTTP เบื้องต้นบน Go ก็รู้สึกว่า มันก็ไม่ได้มีอะไรซับซ้อน เทียบกับตัว Node.js + Express เดี๋ยววันต่อๆไป จะลองไปใช้ Framework หรือกลับไปทบทวน Fundamental Go ต่อ เพราะเอาจริงๆ ขนาดการสร้าง collections, map, การทำ JSON ยังทำไม่เป็น ต้องไปอ่านตัวอย่าง 😅

สุดท้าย Source Code ที่เรียนวันนี้ อัพไว้ใน Github ไฟล์ simple-http.go

Source Code

Happy Coding ❤️

Tags

Chai Phonbopit

เป็น Web Dev ทำงานมา 10 ปีหน่อยๆ ด้วยภาษา JavaScript, Node.js, React, Vue และปัจจุบันกำลังสนใจ Web3, Crypto และ Blockchain เขียนบล็อกที่ https://devahoy.com