This repo contains a Go package for an SMS segments calculator. The package replicates Twilio's SMS segmentation logic, telling you how many segments a message will use, which encoding is required (GSM-7 or UCS-2), and how many characters and bits the message consumes.
Install the package:
go get github.com/tuanphuong-dev/twilio-segment-calculatorSample usage:
package main
import (
"fmt"
segcalculator "github.com/tuanphuong-dev/twilio-segment-calculator"
)
func main() {
msg, err := segcalculator.NewSegmentedMessage("Hello World")
if err != nil {
panic(err)
}
fmt.Println(msg.EncodingName) // "GSM-7"
fmt.Println(msg.SegmentsCount()) // 1
}You can also run the example from the examples/basic folder:
go run ./examples/basicNewSegmentedMessage(message string, opts ...Option) (*SegmentedMessage, error)message: Body of the SMSopts: Optional options, such as encoding or smart encoding
EncodingName— returns the name of the calculated encoding for the message:GSM-7orUCS-2SegmentsCount()— number of segment(s)TotalSize()— total size of the message in bits (including User Data Header if present)MessageSize()— total size of the message in bits (excluding User Data Header if present)GetNonGsmCharacters()— returns a slice of non-GSM-7 characters in the message
By default, NewSegmentedMessage uses segcalculator.Auto to pick the most appropriate encoding. You can force GSM-7 or UCS-2:
msg, err := segcalculator.NewSegmentedMessage(
body,
segcalculator.Encoding(segcalculator.GSM7),
)If you force GSM7 and the message contains non-GSM characters, an error is returned.
Enable a "smart encoding" mode to replace visually similar characters with GSM-7 equivalents:
msg, err := segcalculator.NewSegmentedMessage(
body,
segcalculator.SmartEncoding(true),
)Use GetNonGsmCharacters to see which characters forced the message into UCS-2:
nonGsm := msg.GetNonGsmCharacters()
if len(nonGsm) > 0 {
fmt.Println("Non-GSM characters:", nonGsm)
}To test the library, run the script in examples/basic:
go run ./examples/basicThis code is open source and welcomes contributions. All contributions are subject to our Code of Conduct.
The source code for the library is in the root directory. Before submitting a PR:
- Run linter using
go vet ./...and make sure there are no linter errors - Run tests using
go test ./...and make sure all tests pass
No warranty expressed or implied. Software is as is.