Open1

毎日アウトプット(2022)開発編

schnellschnell

開発に関わる知識を毎日勉強して簡単にアウトプットする。

1/1

go moduleを使った開発の初期設定のようなもの

毎回goプロジェクトを作成するたびに調べ直しているので記す。[参考記事]

# プロジェクトリポジトリに入る
go mod init "プロジェクト名"

これでokプロジェクト名はモジュールとして公開する場合はgithubのリポジトリのアドレスなどを指定する。
外部公開予定のモジュールを開発の都合一時的にローカルから読み込むときは

go mod edit -replace example.com/greetings=../greetings

のように該当モジュールの相対パスを上書きする。

1/2

go言語は以下も参考になる
https://gobyexample.com/

go言語でhttpサーバーを立てる

http.ResponseWriterはクライアントへの返却内容を、http.Requestはクライアントからのリクエストを管理する。

main.go
package main

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

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

これを実行してhttp://localhost:8080/foobarにアクセスすると"foobar"が表示される。
また、index.htmlを作成してそれを表示することもできる。

main.go
package main

import (
	"html/template"
	"log"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("index.html")
	t.Execute(w, nil)
}

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

1/3

golangのhttp.Request型に関して

上記のサンプルコードの通り、クライアントからのリクエストの内容を取り扱うデータ型
https://pkg.go.dev/net/http#Request

type Request struct {
	// HTTPメソッドを格納(GET, POST, PUT, etc...)
	Method string

	// リクエストされたURL
	URL *url.URL

	// プロトコル
	Proto      string // "HTTP/1.0"
	ProtoMajor int    // 1
	ProtoMinor int    // 0

	// リクエストヘッダーを格納
	// Host: example.com
	//	accept-encoding: gzip, deflate
	//	Accept-Language: en-us
	//	fOO: Bar
	//	foo: two
	//
	// then
	//
	//	Header = map[string][]string{
	//		"Accept-Encoding": {"gzip, deflate"},
	//		"Accept-Language": {"en-us"},
	//		"Foo": {"Bar", "two"},
	//	}
	Header Header

	Body io.ReadCloser
}

1/4

clinet.go
package main

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

func main() {

    resp, err := http.Get("http://gobyexample.com")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("Response status:", resp.Status)

    scanner := bufio.NewScanner(resp.Body)
    for i := 0; scanner.Scan() && i < 5; i++ {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        panic(err)
    }
}

1/5

卒論執筆のため休憩