[Golang]net/http를 사용하여 요청 제목의 속성에 여러 개의 값을 부여할 때의 주의점
                                            
                                                
                                                
                                                
                                                
                                                
                                                 14004 단어  Go
                    
개요 net/http 라이브러리로 요청을 보낼 때 내용 유형에 여러 개의 값을 저장하고 요청하고자 합니다.
무슨 일이야?
예를 들어, 컨텐츠 유형에서
content-type=application/json;charset=Shift_JIS`
결론 content-type=application/json;charset=Shift_JIS
위에서 말한 바와 같이;요청 제목에 구분된 값을 추가하여 보내려면net/http 라이브러리에서 다음과 같이 기술합니다.
main.go(略)
header := http.Header{}
header.Set("Content-Type", "application/json;charset=Shift_JIS")
(略)
아래와 같이 기술한 상황에서 구상의 값이 되지 않는다.
main.go(略)
header := http.Header{}
header.Set("Content-Type", "application/json")
header.Add("Content-Type", "charset=Shift_JIS")
(略)
검증 
클라이언트, 서버의 응용 프로그램을 써서 요청 제목의 내용을 살펴보았다.
클라이언트
 
Golang 버전은 go1.11.2 darwin/amd64main.gopackage main
import (
    "bytes"
    "fmt"
    "net/http"
    "github.com/labstack/echo"
)
func main() {
    client := &http.Client{}
    header := http.Header{}
    header.Set("Content-Type", "application/json")
    header.Add("Content-Type", "charset=Shift_JIS")  // 今回問題の箇所
    req, _ := http.NewRequest(
        echo.POST,
        "http://localhost:3000",
        bytes.NewBufferString("hoge"),
    )
    req.Header = header
    client.Do(req)
}
서버
 
node 버전은 v9.11.2server.jsvar http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
    try {
        console.log('requested.');
        console.log('method: ' + req.method);
        console.log('url: ' + req.url);
        console.log('query: %j', url.parse(req.url, true).query);
        console.log('user agent: ' + req.headers['user-agent']);
        console.log('header' + JSON.stringify(req.headers));
    }
    catch (err) {
        console.error('unhandled exception has occured.');
        console.error(err);
    }
    finally {
        res.end();
    }
});
server.listen(3000, function () {
    console.log('http server is running...press enter key to exit.');
    process.stdin.on('data', function (data) {
        if (data.indexOf('\n') !== -1) {
            server.close(function () {
                console.log('http server closed.');
                process.exit(0);
            });
        }
    });
});
server.on('error', function (err) {
    console.error(err);
    process.exit(1);
});
검증 프로세스
 
서버 응용 프로그램을 시작합니다.$ node server.js
클라이언트 응용 프로그램 실행$ go run main.go
서버 로그
 $ node server.js
http server is running...press enter key to exit.
requested.
method: POST
url: /
query: {}
user agent: Go-http-client/1.1
header{"host":"localhost:3000","user-agent":"Go-http-client/1.1","content-length":"4","content-type":"application/json","accept-encoding":"gzip"}
헤더의 content-type,charset=Shift_JIS 없어요...? 
 
조립 요청 제목 수정 처리
 
main.go(略)
header := http.Header{}
header.Set("Content-Type", "application/json;charset=Shift_JIS")
(略)
서버 로그
 http server is running...press enter key to exit.
requested.
method: POST
url: /
query: {}
user agent: Go-http-client/1.1
header{"host":"localhost:3000","user-agent":"Go-http-client/1.1","content-length":"4","content-type":"application/json;charset=Shift_JIS","accept-encoding":"gzip"}
기대했던 대로.
net/http 라이브러리의 Header.Add은;(분호) 구분자는 조립되지 않은 내용의 유형을 표시합니다.
참고 문헌
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여([Golang]net/http를 사용하여 요청 제목의 속성에 여러 개의 값을 부여할 때의 주의점), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/harhogefoo/items/bc7a904e3bdfb0d5a847
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
content-type=application/json;charset=Shift_JIS
(略)
header := http.Header{}
header.Set("Content-Type", "application/json;charset=Shift_JIS")
(略)
(略)
header := http.Header{}
header.Set("Content-Type", "application/json")
header.Add("Content-Type", "charset=Shift_JIS")
(略)
클라이언트, 서버의 응용 프로그램을 써서 요청 제목의 내용을 살펴보았다.
클라이언트
Golang 버전은
go1.11.2 darwin/amd64main.gopackage main
import (
    "bytes"
    "fmt"
    "net/http"
    "github.com/labstack/echo"
)
func main() {
    client := &http.Client{}
    header := http.Header{}
    header.Set("Content-Type", "application/json")
    header.Add("Content-Type", "charset=Shift_JIS")  // 今回問題の箇所
    req, _ := http.NewRequest(
        echo.POST,
        "http://localhost:3000",
        bytes.NewBufferString("hoge"),
    )
    req.Header = header
    client.Do(req)
}
서버
node 버전은
v9.11.2server.jsvar http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
    try {
        console.log('requested.');
        console.log('method: ' + req.method);
        console.log('url: ' + req.url);
        console.log('query: %j', url.parse(req.url, true).query);
        console.log('user agent: ' + req.headers['user-agent']);
        console.log('header' + JSON.stringify(req.headers));
    }
    catch (err) {
        console.error('unhandled exception has occured.');
        console.error(err);
    }
    finally {
        res.end();
    }
});
server.listen(3000, function () {
    console.log('http server is running...press enter key to exit.');
    process.stdin.on('data', function (data) {
        if (data.indexOf('\n') !== -1) {
            server.close(function () {
                console.log('http server closed.');
                process.exit(0);
            });
        }
    });
});
server.on('error', function (err) {
    console.error(err);
    process.exit(1);
});
검증 프로세스
서버 응용 프로그램을 시작합니다.
$ node server.js
$ go run main.go
서버 로그
$ node server.js
http server is running...press enter key to exit.
requested.
method: POST
url: /
query: {}
user agent: Go-http-client/1.1
header{"host":"localhost:3000","user-agent":"Go-http-client/1.1","content-length":"4","content-type":"application/json","accept-encoding":"gzip"}
 
 조립 요청 제목 수정 처리
main.go
(略)
header := http.Header{}
header.Set("Content-Type", "application/json;charset=Shift_JIS")
(略)
서버 로그
http server is running...press enter key to exit.
requested.
method: POST
url: /
query: {}
user agent: Go-http-client/1.1
header{"host":"localhost:3000","user-agent":"Go-http-client/1.1","content-length":"4","content-type":"application/json;charset=Shift_JIS","accept-encoding":"gzip"}
net/http 라이브러리의
Header.Add은;(분호) 구분자는 조립되지 않은 내용의 유형을 표시합니다.참고 문헌
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여([Golang]net/http를 사용하여 요청 제목의 속성에 여러 개의 값을 부여할 때의 주의점), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/harhogefoo/items/bc7a904e3bdfb0d5a847
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
Reference
이 문제에 관하여([Golang]net/http를 사용하여 요청 제목의 속성에 여러 개의 값을 부여할 때의 주의점), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/harhogefoo/items/bc7a904e3bdfb0d5a847텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)