Convert string to int by Golang!

Golang strconv package is designed for string conversation process. 

strconv.Atoi(str)
Example: 

nmb,err:=strconv.Atoi("12345")
if err!=nil{
   panic(err)
}

String to Int 

strconv.Atoi(str) method converts string to integar base on 10. it's same thing as strconv.ParseInt(str,10,0)

strconv.ParseInt(str,base,bitSize) additionally can parse on base 2,8,16. 

Int parse modes

If the base argument is 0, the true base is implied by the string's.

Prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o".

16 for "0x", and 10 otherwise. Also, for argument base 0 only,


n, err := strconv.ParseInt("0Xf1af", 0, 64)
fmt.Println(n, err)

result :: 61871 <nil>

About me

I have been started working on my blog project. I remember when I started writing my posts almost 7 years ago. Recently I was looking photos on my old laptop I saw my old blog database, and I looked what I did 7 years ago. I made a lot of errors due to lack of experience.

I think writing is not easy thing. it needs more experience, planning, language skills. I don't know how much good writer am I ? I know that I make a lot of errors, but to be honest I don't care so much. Mistakes might be teacher.

My goal is publishing high quality content has been written from myself. I believe that nowadays with AI, cheap writing is much more easier but finding high quality content is getting much much more hard.

My another goal is making connection people have similar interest with me. Of course, social media helps us in many case, however it comes problem with itself. A lot of people make promotions of their own companies. Specially in Linkedin. To be honest, I don't want to promote anyone or any company.

On the other hand, sometimes whatever we know or experienced, we could miss simple details. Simplicity is really interesting topic. I believe that simple is difficult. I want to be simple as much as I can. 


Http status codes: 400 Bad request

Http is stateless protocol that client ask precise information to server. Then server returns response according to request content

If client send unexpected content, server returns 400 Bad request

Http status codes declared for communication between client and server by The Internet Assigned Numbers Authority

http status 400 belongs to 4xx client error – the request contains bad syntax or cannot be fulfilled

What is meaning 503 service unavailable ?

503 service unavailable (http 503) error code is one of the most most popular http codes

What's meaning 503 service unavailable ?

503 service unavailable occurs when http server is busy and it can't handle your request

How can I fix 503 service unavailable ?

One way of solving 503 service unavailable contacting website administrator. Also periodically trying to connect website can help, because sometimes server might unable to response

My Info

you can contact me from contact form

Contract

abdullah.gurlek3 at gmail.com

Find period between two times with golang

Golang time package provides rich time handling functionality.

Duration type represents passed time between two concrete dates.

start := time.Now()
end := time.Now().AddDate(0, 1, 11)
duration := end.Sub(start)
fmt.Printf("Duration between %v and %v is %v", start, end, duration)
result :
> Duration between 2025-02-16 13:01:16.870769 +0100 CET m=+0.000735054 and 2025-03-27 13:01:16.870769 +0100 CET is 936h0m0s

Sub method returns Duration object has period between firs date and second date. if first date is before than second date, result would be negative

Golang json Marshalling operations - convert object to json string

encoding/json package provides json operations.

Marshalling

Marshalling means converting object to json.

Marshalling array
myArray := []string{"test 1", "test 2", "test 3"}
jsonStr, err := json.Marshal(myArray)
fmt.Println(string(jsonStr), err)
result :

["test 1","test 2","test 3"] <nil>

Marshalling Map
myMap := make(map[string]interface{})
myMap["key 1"] = "val 1"
myMap["key 2"] = "val 2"
myMap["key int"] = 1234
myMap["key bool"] = true

jsonStr, err := json.Marshal(myMap)
fmt.Println(string(jsonStr), err)
result :

{"key 1":"val 1","key 2":"val 2","key bool":true,"key int":1234} <nil>

Marshalling Object
type TestObj struct {
	FieldStr             string
	FieldInt             int
	FieldMightNullString *string
	SubTestObj           *TestObj
}

testStr := "Might null field"
myTestObj := TestObj{
	FieldStr:             "test str",
	FieldInt:             1,
	FieldMightNullString: &testStr,
	SubTestObj: &TestObj{
		FieldStr: "Test str sub",
		FieldInt: 2},
}

jsonStr, err := json.Marshal(myTestObj)
fmt.Println(string(jsonStr), err)
result :

{"FieldStr":"test str","FieldInt":1,"FieldMightNullString":"Might null field","SubTestObj":{"FieldStr":"Test str sub","FieldInt":2,"FieldMightNullString":null,"SubTestObj":null}} <nil>

Marshalling as human readable text (json pretty print)

MarshalIndent function provides to generate pretty printed output

... 
jsonStr, err := json.MarshalIndent(myTestObj, "  ", "  ")
fmt.Println(string(jsonStr), err)
output :
{
    "FieldStr": "test str",
    "FieldInt": 1,
    "FieldMightNullString": "Might null field",
    "SubTestObj": {
      "FieldStr": "Test str sub",
      "FieldInt": 2,
      "FieldMightNullString": null,
      "SubTestObj": null
    }
  } <nil>

Compressing directory with to Zip file with Golang

Golang version 1.23.6 supporting tar and zip compressing. In this article I will show you how to compress directory with Golang

Creating a output file

First we need to create output file.

filename := "test.zip"
output_file, err := os.Create(filename)
if err != nil {
	panic(err)
}

if you want to compress with tar file, you can replace extension to the .tar

Creating a writer
w := zip.NewWriter(output_file)
defer w.Close()
creating new file under the zip stream
path := "helloworld.txt"
zipFile, err := w.Create(path)
if err != nil {
	panic(err)
}
Writing to the zip stream
myBytes := []byte("hello world !")
zipFile.Write(myBytes)
let's see output
> unzip -l test.zip  
  Length      Date    Time    Name
---------  ---------- -----   ----
       13  00-00-1980 00:00   helloworld.txt
---------                     -------
       13                     1 file
>  zipinfo test.zip

Archive:  test.zip
Zip file size: 161 bytes, number of entries: 1
-rw----     2.0 fat       13 bl defN 80-000-00 00:00 helloworld.txt
1 file, 13 bytes uncompressed, 19 bytes compressed:  -46.2%
> unzip -p test.zip helloworld.txt 

hello world !%                                   

Writing header metadata

CreateHeader method provides creating new zip file with metadata in stream

zipFile, err := w.CreateHeader(&zip.FileHeader{
	Name:     path,
	Comment:  "Test Comment",
	Modified: time.Now()},
)
let's check out again the zip file :
> zipinfo test.zip

Archive:  test.zip
Zip file size: 185 bytes, number of entries: 1
-rw----     2.0 fat       13 bX stor 25-Feb-07 14:35 helloworld.txt
1 file, 13 bytes uncompressed, 13 bytes compressed:  0.0%

we can see that file modification date is updated

Fahrenheit to Celsius converter

Fahrenheit to Celsius conversation

Fahrenheit is most popular temperature scale in USA designed in 1724 by the Physicist Gabriel Fahrenheit

 Fahrenheit = (Celsius-32) * (5/9)
Examples

32 Fahrenheit equals 0 Celsius

212 Fahrenheit equals 100 Celsius (water boiling)

Convert date to timestamp by Golang

What is Unix timestamp ?

Unix timestamp is 64 bit value represents current time since 1 January 1970

Golang time.Now() returns current DateTime object

Getting timestamp in Golang
currentTime := time.Now()
fmt.Println(currentTime.Unix())

> 1738148999

UnixMilli
currentTime := time.Now()
fmt.Println(currentTime.UnixMilli())

> 1738149111065

UnixMicro
currentTime := time.Now()
fmt.Println(currentTime.UnixMicro())

> 1738149141680690

UnixNano
currentTime := time.Now()
fmt.Println(currentTime.UnixNano())

> 1738149218711926000