如何在Go中将十六进制字节写入文本文件?

I want to log port I/O operations to text file with Go language. I wrote such a function:

func trace (buffer []byte){

    f, err := os.OpenFile("trace.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return
    }
    defer f.Close()

    for _, val := range buffer{         
        if _, err := f.Write([]byte{val});err!=nil{return}    
    }
}

But f.Write method writes to file ASCII string equivalent, but not []byte values. I need hexadecimal values, not strings in my log. I can not understand, why code f.Write([]byte{"string"}) is valid, but something like f.Write([]byte{fmt.Spirintf("%x", val)}) does not compile...

If I understood correctly your question, you are looking for a solution to write to log the hexadecimal value of an ASCII string? ex. "41" == { 0x34, 0x31 }? If so, the code you are looking for is:

f.Write([]byte(fmt.Sprintf("%x", buffer )))

Fnally, my working code is:

func trace (buffer []byte){

    if !Debug{return}

    f, err := os.OpenFile("trace.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return
    }
    defer f.Close()

    date:=fmt.Sprintf("%v", time.Now().Format("2018-01-02 15:01:02 PM Jan Mon"))

    if _, err := f.Write([]byte(date+"
"));err!=nil{return}

    var counter int = 0

    for _, val := range buffer{
        if counter == 16{
            if _, err := f.Write([]byte("
"));err!=nil{return}
            counter=0
        }

        fmt.Fprintf(f, "%02x ", val)
        counter++
    }

    if _, err := f.Write([]byte("

"));err!=nil{return}

}